const Koa = require('koa');
const app = new Koa()
const path = require('path')
const bodyParser = require('koa-bodyparser');
// const ejs = require('ejs');
const session = require('koa-session-minimal');
const MysqlStore = require('koa-mysql-session');
const config = require('./config/default.js');
// const router = require('koa-router')
// const views = require('koa-views')
// const koaStatic = require('koa-static')
// const cors = require('koa2-cors');
const koaSwagger = require('koa2-swagger-ui')
const staticCache = require('koa-static-cache')
const swagger = require('./util/swagger')

app.use(koaSwagger({
    routePrefix: '/swagger', // host at /swagger instead of default /docs
    swaggerOptions: {
        url: '/swagger.json', // example path to json 其实就是之后swagger-jsdoc生成的文档地址
    },
}))

// session存储配置
const sessionMysqlConfig = {
    user: config.database.USERNAME,
    password: config.database.PASSWORD,
    database: config.database.DATABASE,
    host: config.database.HOST,
}

// 配置session中间件
app.use(session({
    key: 'USER_SID',
    store: new MysqlStore(sessionMysqlConfig)
}))


// 配置静态资源加载中间件
// app.use(koaStatic(
//   path.join(__dirname , './public')
// ))
// 缓存
app.use(staticCache(path.join(__dirname, './public'), { dynamic: true }, {
    maxAge: 365 * 24 * 60 * 60
}))
app.use(staticCache(path.join(__dirname, './images'), { dynamic: true }, {
    maxAge: 365 * 24 * 60 * 60
}))

// 配置服务端模板渲染引擎中间件
// app.use(views(path.join(__dirname, './views'), {
//   extension: 'ejs'
// }))
app.use(bodyParser({
    formLimit: '1mb'
}))



// app.use(cors());
app.use(async(ctx, next) => {
    ctx.set('Access-Control-Allow-Origin', '*');
    ctx.set('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    ctx.set('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
    if (ctx.method == 'OPTIONS') {
        ctx.body = 200;
    } else {
        await next();
    }
});

//  路由
app.use(swagger.routes(), swagger.allowedMethods())
app.use(require('./router/user').routes())
app.use(require('./router/signin').routes())
app.use(require('./router/signup').routes())
app.use(require('./router/posts').routes())
app.use(require('./router/signout').routes())




// app.listen(config.port)

// console.log(`listening on port ${config.port}`)

module.exports = app